/*
 * AdapterListener.cpp
 *
 *  Created on: Jul 15, 2008
 *      Author: Kyle
 */

#include "AdapterListener.h"

AdapterListener::AdapterListener(pcap_t *_adapter)
	: adapter(_adapter) {


}

boost::thread *AdapterListener::getThread() {
	return thread;
}

AdapterListener::~AdapterListener() {

}

void AdapterListener::run() {
	thread = new boost::thread(*this);
}

void AdapterListener::operator ()() {
//	printf("\nding...?");
//	pcap_loop(adapter, 0, &AdapterListener::parse, NULL);
//	while(true) {
//		Sleep(1000);
//		printf("\nding...!");
//	}
	int rc;
	pcap_pkthdr *header;
	const u_char *pkt_data;
	while(true) {
		if (rc = pcap_next_ex(adapter, &header, &pkt_data) >= 0) {
			if (rc == 0) {	// timeout
				continue;
			} else {
			    struct tm *ltime;
			    char timestr[16];
			    time_t local_tv_sec;

			    /* convert the timestamp to readable format */
			    local_tv_sec = header->ts.tv_sec;
			    ltime=localtime(&local_tv_sec);
			    strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
			    //Event* e = Protocol::parse((char*)(pkt_data + MSNMS_OFFSET));
			    if (header->len >  TCPIP_DATA_OFFSET + 10) {
			    	if (strstr((char*)(pkt_data + TCPIP_DATA_OFFSET), "MSG")) {
						printf("\n********************\n");

							for (size_t i = TCPIP_DATA_OFFSET; i < header->len; i++) {
								printf("%c", pkt_data[i]);
							}
						printf("\n********************");
			    	}
			    }
			}


		}
	}
}


void AdapterListener::parse(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data)
{
    struct tm *ltime;
    char timestr[16];
    time_t local_tv_sec;

    /* convert the timestamp to readable format */
    local_tv_sec = header->ts.tv_sec;
    ltime=localtime(&local_tv_sec);
    strftime( timestr, sizeof timestr, "%H:%M:%S", ltime);
    //Event* e = Protocol::parse((char*)(pkt_data + MSNMS_OFFSET));

    if (header->len >  TCPIP_DATA_OFFSET + 10) {
    	if (strstr((char*)(pkt_data + TCPIP_DATA_OFFSET), "MSG")) {
			printf("\n********************\n");

				for (size_t i = TCPIP_DATA_OFFSET; i < header->len; i++) {
					printf("%c", pkt_data[i]);
				}
			printf("\n********************");
    	}
    }
}

